<?php
/**
 * @file pdf_functions.php
 * @brief Provides functions for PDF file modification
 */
 
//load fpdf libraries
require_once(ROOT_DIR.'/lib/fpdf17/fpdf.php'); 
require_once(ROOT_DIR.'/lib/fpdi_lib/fpdi.php'); 
require_once('../quote/class.quote_settings.php');
/**
generates the quote pdf file from template

@param 
	$output_format output method after pdf is genreated
	$inlist_items boolean value for style of quote (0 = items listed in separate page, price list will not include items; 1 = items are listed in price list)
	$file_path file path to store the temperory file for sending emails
*/
$lc = 0;
$margin_top = 10;
$margin_top_page = 20;
function generatePDF($output_format='I', $inlist_items, $file_path=''){
	global $lc;
	$qs = new QuoteSettings();
	$pdf = new FPDI();
	$template_file = TEMPLATE_QUOTE_FILE;
	$total_num_pages = $pdf->setSourceFile($template_file); 
	$pdf->SetAutoPageBreak(false);
	$lc = 0;
	
	$count_first = $qs->getSetting('settings','count_first');
	
	$starting_page = ($count_first) ? $qs->getSetting('settings','start_page') : $qs->getSetting('settings','start_page')+1; //skip how many pages before overprint
	
	for($i=1 ; $i<=$total_num_pages ; $i++){
		$pdf->AddPage(); 
		if($i == $starting_page){
			createQuotePages($pdf,$inlist_items);
		}else{
			$tplIdx = $pdf->importPage($i); 
			$pdf->useTemplate($tplIdx, 0, 0, 0);
		}
	}
	
	//output pdf files
	//I - standard output
	//D - force download
	//F - save to local file
	//S - return as a string
	if($output_format == 'F'){
		$pdf->Output($file_path, $output_format);
	}else{
		$pdf->Output($template_file, $output_format);
	}
}

function createQuotePages($pdf, $inlist_items){
	$_POST = cleanPost($_POST);
	$num_selected_category = $_POST['num_selected_category'];
	$num_selected_item = $_POST['num_selected_item'];
	
	//ITEM DESCRIPTION SECTION
	if($inlist_items == 0){
		writeSectionTitle($pdf,'ITEM DESCRIPTION');
		for($i=1; $i<=$num_selected_category;$i++){
			$cat_id = $_POST['category_no_'.$i];
			$category = getCategoryById($cat_id);
			writeLine($pdf,'CATEGORY',$cat_id);
			if($category['note']!=''){
				writeLine($pdf,'CATEGORY_NOTE',$cat_id);
			}
			$items = getItems($cat_id);
			
			for($j=1;$j<=$num_selected_item;$j++){
				$item_id = $_POST['item_no_'.$j];
				$qty = $_POST['qty_no_'.$j];
				foreach($items as $item){
					if($item['id'] == $item_id){
						writeLine($pdf, 'ITEM_NAME', $item_id);
						if($item['note']!=''){
							writeLine($pdf, 'ITEM_NOTE', $item_id);
						}
					}
				}//end foreach loop
			}//end iteration loop on $j
		}
		
		//start a new page and reset line counter
		$pdf->AddPage(); 
		$lc = 0;
	}
	
	//COST ESTIMATE SECTION
	writeSectionTitle($pdf, 'COST ESTIMATE');
	for($i=1; $i<=$num_selected_category;$i++){
		$cat_id = $_POST['category_no_'.$i];
		$category = getCategoryById($cat_id);
		$items = getItems($cat_id);
		
		//echo '<strong>'.$category['name'].'</strong><br />';
		
		//writeLine($pdf ,$category['name'],'CATEGORY');
		writeLine($pdf,'CATEGORY',$cat_id);
		if($category['note']!=''){
			writeLine($pdf,'CATEGORY_NOTE',$cat_id);
		}
		for($j=1;$j<=$num_selected_item;$j++){
			if($inlist_items == 1):
				$item_id = $_POST['item_no_'.$j];
				$qty = $_POST['qty_no_'.$j];
				foreach($items as $item){
					if($item['id'] == $item_id){
						writeLine($pdf, 'ITEM', $item_id,$qty);
						if($item['note']!=''){
							writeLine($pdf, 'ITEM_NOTE', $item_id);
						}
					}
				}
			endif;
		}
		
		$cat_hour = $_POST['cat_hour_'.$i];
		$cat_price = $_POST['cat_price_'.$i];
		writeLine($pdf,'CATEGORY_TOTAL',$cat_id,0,$cat_hour,$cat_price);
		
	}
	
	//print total price
	$sub_total_value = $_POST['sub_total_value'];
	writeLine($pdf,'SUB_TOTAL',$cat_id,0,0,0,$sub_total_value);
	if(isset($_POST['gst'])){
		$GST_value = $_POST['gst']; 
		writeLine($pdf,'GST',$cat_id,0,0,0,$GST_value);
	}	
	$total_price = $_POST['total_price'];
	writeLine($pdf,'TOTAL',$cat_id,0,0,0,$total_price);
	
}
/**
write a line of text using fpdf write function

@param $pdf
	the FPDF object to handle pdf modification
@param $type
	what type of text is being written 
	accepted strings:
		CATEGORY
		CATEGORY_NOTE
		ITEM
		ITEM_NAME
		ITEM_NOTE
		CATEGORY_TOTAL
		TOTAL
		GST
		SUB_TOTAL
		
@param $id
	the item id or category id used to grab information
	
@param $qty 
	quantity value for items
	
@param $cat_total_hour
	total number of hours for one category
	
@param $cat_total_price
	price value for one category
	
@param $total_price
	total price value

*/

function writeLine($pdf,$type,$id,$qty=0,$cat_total_hour=0,$cat_total_price=0,$total_price=0){
	global $lc,$margin_top_page,$margin_top; 
	$qs = new QuoteSettings();
	$line_height = 5;
	$start_x = 10;
	$start_y = $line_height * $lc +$margin_top_page + $margin_top;
	$pdf -> SetXY($start_x, $start_y);
	
	if($type=='CATEGORY'){
		//font = Arial Bold size 14 points, color= blue
		$style = $qs->getStyle('cat_title');
		$pdf->SetFont($style['font'], $style['font_style'], $style['size']); 
		$color = hex2rgb($style['color']);
		$pdf->SetTextColor($color[0],$color[1],$color[2]);
		
		$category = getCategoryById($id);
		
		//name part
		$str = '';
		$name_length_limit = 40;
		
		$str .= $category['name'];
		
		$num_space_name = $name_length_limit - strlen($category['name']);
		for($i=0;$i<$num_space_name;$i++){
			//$str.=' ';
		}
		$pdf->Write($line_height * $lc, $str);
		
		//price part
		$str = '';
		$price_x = 150;
		$price_y = 10;//first line y coordinate
		$rate_length_limit = 10;
		$str.= '$'.$category['rate'].' / hour';
		$pdf -> SetX($price_x);
		$pdf->Write($line_height * $lc, $str);
		
		
	}else if($type=='ITEM'){
		//font = Arial Italic size 12 points, color= black
		$style = $qs->getStyle('item_title');
		$pdf->SetFont($style['font'], $style['font_style'], $style['size']); 
		$color = hex2rgb($style['color']);
		$pdf->SetTextColor($color[0],$color[1],$color[2]);
		
		
		$item = getItemById($id);
		//name part
		$str = '';
		$name_length_limit = 40;
		
		$str .= $qty.' x ';
		$str .= $item['name'];
		
		$num_space_name = $name_length_limit - strlen($item['name']);
		for($i=0;$i<$num_space_name;$i++){
			//$str.=' ';
		}
		$pdf->Write($line_height * $lc, $str);
		
		if($item['show_hour']=='1'){
			//hours part
			$str = '';
			$price_x = 150;
			$rate_length_limit = 10;
			$str.= $item['hours_per_item'].' hour(s) / item';
			$pdf -> SetX($price_x);
			$pdf->Write($line_height * $lc, $str);
		}
		
		
	}else if($type=='ITEM_NAME'){
		//font = Arial Italic size 12 points, color= black
		$style = $qs->getStyle('item_title');
		$pdf->SetFont($style['font'], $style['font_style'], $style['size']); 
		$color = hex2rgb($style['color']);
		$pdf->SetTextColor($color[0],$color[1],$color[2]);
		
		$indent_x = 15;
		$pdf -> SetX($indent_x);
		
		$item = getItemById($id);
		//name part
		$str = '';
		$name_length_limit = 40;
		
		$str .= $item['name'];
		
		$num_space_name = $name_length_limit - strlen($item['name']);
		for($i=0;$i<$num_space_name;$i++){
			//$str.=' ';
		}
		$pdf->Write($line_height * $lc, $str);
		
		if($item['show_hour']=='1'){
			//hours part
			$str = '';
			$price_x = 150;
			$rate_length_limit = 10;
			$str.= $item['hours_per_item'].' hour(s) / item';
			$pdf -> SetX($price_x);
			$pdf->Write($line_height * $lc, $str);
		}
		
		
	}else if($type == 'CATEGORY_NOTE'){
		//set font
		$style = $qs->getStyle('cat_desc');
		$pdf->SetFont($style['font'], $style['font_style'], $style['size']); 
		$color = hex2rgb($style['color']);
		$pdf->SetTextColor($color[0],$color[1],$color[2]);
		//get category info
		$category = getCategoryById($id);
		
		$indent_x = 15;
		$pdf -> SetX($indent_x);
		
		$str = '';
		$str.= $category['note'];
		$pdf->Write($line_height * $lc, $str);
		
	}else if($type == 'ITEM_NOTE'){
		//set font
		$style = $qs->getStyle('item_desc');
		$pdf->SetFont($style['font'], $style['font_style'], $style['size']); 
		$color = hex2rgb($style['color']);
		$pdf->SetTextColor($color[0],$color[1],$color[2]);
		//get item info
		$item = getItemById($id);
		
		$indent_x = 25;
		$pdf -> SetX($indent_x);
		
		$str = '';
		$str.= $item['note'];
		$pdf->Write($line_height * $lc, $str);
		
	}else if($type == 'CATEGORY_TOTAL'){
		//set font
		$style = $qs->getStyle('summary');
		$pdf->SetFont($style['font'], $style['font_style'], $style['size']); 
		$color = hex2rgb($style['color']);
		$pdf->SetTextColor($color[0],$color[1],$color[2]);
		
		$length_limit = 120;
		$str = '';
		$str.= 'Total '.$cat_total_hour.' hours'; 
		$indent_x = $length_limit - strlen($str);
		$pdf -> SetX($indent_x);
		$pdf->Write($line_height * $lc, $str);
		$str = '= $'.$cat_total_price;
		$pdf->Write($line_height * $lc, $str);
		
	}else if($type == 'TOTAL'){
		//set font
		$style = $qs->getStyle('summary');
		$pdf->SetFont($style['font'], $style['font_style'], $style['size']); 
		$color = hex2rgb($style['color']);
		$pdf->SetTextColor($color[0],$color[1],$color[2]);
		
		$length_limit = 140;
		$str = '';
		$str.= 'Total: $'.$total_price;
		$indent_x = $length_limit - strlen($str);
		$pdf -> SetX($indent_x);
		$pdf->Write($line_height * $lc, $str);
	}else if($type == 'GST'){
		//set font
		$style = $qs->getStyle('summary');
		$pdf->SetFont($style['font'], $style['font_style'], $style['size']); 
		$color = hex2rgb($style['color']);
		$pdf->SetTextColor($color[0],$color[1],$color[2]);
		
		
		$length_limit = 140;
		$str = '';
		$str.= 'GST: $'.$total_price;
		$indent_x = $length_limit - strlen($str);
		$pdf -> SetX($indent_x);
		$pdf->Write($line_height * $lc, $str);
	}else if($type == 'SUB_TOTAL'){
		//set font
		$style = $qs->getStyle('summary');
		$pdf->SetFont($style['font'], $style['font_style'], $style['size']); 
		$color = hex2rgb($style['color']);
		$pdf->SetTextColor($color[0],$color[1],$color[2]);
		
		$length_limit = 140;
		$str = '';
		$str.= 'Sub total: $'.$total_price;
		$indent_x = $length_limit - strlen($str);
		$pdf -> SetX($indent_x);
		$pdf->Write($line_height * $lc, $str);
	}
	
	//add line counter
	$lc++;
	//page break
	$bottom_margin = 105;//if set to 95, then no bottom space is left on result pdf file
	$height = floor($pdf->h);
	
    $space_left=$height-($pdf->GetY()+$bottom_margin); // space left on page
	//echo $space_left.'<br />';
	if ($line_height > $space_left) {
		$margin_top = 0;
		$pdf->AddPage(); // page break
		$lc = 0;
	}
	
	
}


function writeSectionTitle($pdf,$text){
	global $lc,$margin_top_page; 
	$lc=0;
	$margin_top_page = 10;
	$qs = new QuoteSettings();
	$line_height = 10;
	$start_x = 10;
	$start_y = $margin_top_page;
	$pdf -> SetXY($start_x,$start_y);
	
	//set style
	$style = $qs->getStyle('page_title');
	$pdf->SetFont($style['font'], $style['font_style'], $style['size']); 
	$color = hex2rgb($style['color']);
	$pdf->SetTextColor($color[0],$color[1],$color[2]);
	
	$pdf->Write($line_height * $lc, $text);
	
	$lc++;
}

/*
	converts hex code color to rgb value as an array
*/
function hex2rgb($hex) {
   $hex = str_replace("#", "", $hex);

   if(strlen($hex) == 3) {
      $r = hexdec(substr($hex,0,1).substr($hex,0,1));
      $g = hexdec(substr($hex,1,1).substr($hex,1,1));
      $b = hexdec(substr($hex,2,1).substr($hex,2,1));
   } else {
      $r = hexdec(substr($hex,0,2));
      $g = hexdec(substr($hex,2,2));
      $b = hexdec(substr($hex,4,2));
   }
   $rgb = array($r, $g, $b);
   //return implode(",", $rgb); // returns the rgb values separated by commas
   return $rgb; // returns an array with the rgb values
}

?>